package com.ymatou.authapp.testcase;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.authapp.parameter.LoginAuthBean;
import com.ymatou.authapp.service.LoginAuthCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P2;
import com.ymt.utils.tag.P3;
import com.ymttest.business.data.LoginSafeConfiguration;
import com.ymttest.business.service.UserCallService;
import com.ymttest.database.mongo.MongoLoginHistoryWapper;
import com.ymttest.database.mongo.ULC201406Bean;
import com.ymttest.database.mongo.ULC201406Wapper;
import com.ymttest.database.mongo.UserTokenWapper;
import com.ymttest.database.mongo.YmatouBlacklistUserWapper;
import com.ymttest.database.sqlwapper.LoginHistoryWapper;
import com.ymttest.database.sqlwapper.UserSafeWapper;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.ECode;

/**
 * 登入认证 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_LoginAuth {
	private static LoginAuthBean lab;
	private static LoginAuthCall lac;
	private UserSafeWapper authWapper;
	private ULC201406Wapper userWapper;
	private MongoLoginHistoryWapper mloginHistoryWapper;
	private YmatouBlacklistUserWapper ymtblacklistuserWapper;
	private UserTokenWapper userTokenWapper;
	private static boolean DELETELOGINHISTORY = true;

	@BeforeClass
	public static void setUp() throws Exception {
		Logger.createResultFile("登入认证");
		
	}

	@Before
	public void caseUp() throws Exception {
		lab = new LoginAuthBean();
		lac = new LoginAuthCall();
		authWapper = new UserSafeWapper();
		userWapper = new ULC201406Wapper();
		mloginHistoryWapper=new MongoLoginHistoryWapper();
		ymtblacklistuserWapper=new YmatouBlacklistUserWapper();
		userTokenWapper = new UserTokenWapper();
	}

	@AfterClass
	public static void tearDown() throws Throwable {
		Logger.generateResult(lac.getOpurl());
		
	}

	@After
	public void caseDown() throws Throwable {
		Logger.end();
		userWapper.close();
		authWapper.close();
		mloginHistoryWapper.close();
		ymtblacklistuserWapper.close();
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_LoginAuth_001() {
		Logger.start(true,"注册用户第一次在PC端登陆，登入认证成功");
		try {
			Logger.comment("前置条件准备");
			String phone = TestDataManager.getPhoneNum();
			String email = TestDataManager.getEmail();
			Map UserMap = UserCallService.registerUser(email, phone,null);
			String AccessToken = (String) UserMap.get("token");
			int UserId = (Integer) UserMap.get("userId");
			String UserName = (String) UserMap.get("loginId");
			Thread.sleep(5000);
			HashMap m = new HashMap();
			m.put("Uid", UserId);
			List<Map> list = new LoginHistoryWapper().selectUserRegHistoryByUid(m);
			Logger.verifyEquals(1, list.size(), "验证UserRegHistory表记录");
			
			Logger.comment("开始登陆认证");
			lab.setLoginId(UserName);
			lab.setPas("123456a");
			lab.setSourceType("MainSite");
			lac.setData(lab);
			lab.setClientIp("120.1.1.1");
			lac.callService();
			Logger.verifyEquals(true, lac.getSuccess(), "验证Success");
			Logger.verifyEquals(phone, lac.getUserData().getLoginMobile(), "验证UserName");
			Logger.verifyNotNull(AccessToken, "验证AccessToken");
			Logger.verifyEquals(UserId, lac.getUserData().getUserId(), "验证UserId");
			Logger.verifyEquals(UserName.toLowerCase(), lac.getUserData().getLoginId(), "验证登陆ID");
			Logger.verifyEquals(email.toLowerCase(), lac.getUserData().getLoginMail(), "验证登录邮箱");
			Logger.verifyEquals(AccessToken, lac.getUserData().getSign(), "验证Token信息");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_LoginAuth_002() {
		Logger.start(false,"输入错误LoginId失败");
		try {
			lab.setLoginId("nobody1");
			lab.setPas("123456a");
			lab.setClientIp(TestDataManager.getRandomIp());
			lac.setData(lab);
			lab.setSourceType("MainSite");
			lac.callService();
			Logger.verifyEquals(false, lac.getSuccess(), "验证Success");
			Logger.verifyEquals(ECode.AUTH_WRONG_USERNAME_PWD, lac.getMsg(), "验证Msg信息");
			Logger.verifyEquals("LoingIdOrPasError", new JSONObject(lac.getString("Result")).get("Code"), "验证Code信息");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_LoginAuth_003() {
		Logger.start(false,"输入错误项Pas失败");
		try {
			lab.setLoginId("15216713145");
			lab.setPas("12345");
			lab.setClientIp(TestDataManager.getRandomIp());
			lac.setData(lab);
			lab.setSourceType("MainSite");
			lac.callService();
			Logger.verifyEquals(false, lac.getSuccess(), "验证Success");
			Logger.verifyEquals(ECode.AUTH_WRONG_USERNAME_PWD, lac.getMsg(), "验证Msg信息");
			Logger.verifyEquals("LoingIdOrPasError", new JSONObject(lac.getString("Result")).get("Code"), "验证Code信息");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P2.class)
	@TestCase
	@Ignore//接口变动，后期需要修改
	public void Tc_LoginAuth_004() {
		Logger.start(false,"多次登入认证加入黑名单");
		try {
			for (int i = 0; i <= 9; i++) {
				lab = new LoginAuthBean();
				lac = new LoginAuthCall();
				lab.setLoginId("test007");
				lab.setPas("123456a");
				lab.setClientIp(TestDataManager.getRandomIp());
				lab.setSourceType("MainSite");
				lac.setData(lab);
				lac.callService();
			}
			Logger.verifyEquals(false, lac.getSuccess(), "验证Success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P2.class)
	@TestCase
	@Ignore//接口变动，后期需要修改
	public void Tc_LoginAuth_005() {
		Logger.start(false,"多次登入同ip认证加入黑名单");
		try {
			for (int i = 0; i <= 11; i++) {
				new UserCallService();
				Map UserMap = UserCallService.registerByMobile();
				String UserName = (String) UserMap.get("phone");
				lab = new LoginAuthBean();
				lac = new LoginAuthCall();
				lab.setLoginId(UserName);
				lab.setPas("123456a");
				lab.setClientIp("173.16.100.1");
				lab.setSourceType("MainSite");
				lac.setData(lab);
				lac.callService();
			}
			Logger.verifyEquals(false, lac.getSuccess(), "验证Success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P2.class)
	@TestCase
	@Ignore
	// stg验证用，本地不运行
	public void Tc_LoginAuth_006() {
		Logger.start(true,"白名单多次登入认证");
		try {
			for (int i = 0; i <= 20; i++) {
				// Map UserMap = new UserCallService().registerByMobile();
				String UserName = TestDataManager.getPhoneNum();
				lab = new LoginAuthBean();
				lac = new LoginAuthCall();
				lab.setLoginId(UserName);
				lab.setPas("123456a");
				lab.setClientIp("116.228.41.2");
				lab.setSourceType("MainSite");
				lac.setData(lab);
				lac.callService();
			}
			Logger.verifyEquals(true, lac.getSuccess(), "验证Success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	@Ignore
	//case 无意义 待确认
	public void Tc_LoginAuth_007() {
		Logger.start(true,"登入认证成功");
		try {
			//UserId":20225153,"LoginId":"autotest_ubammm00ef",			
			int UserId =20225153;
			String UserName ="autotest_ubammm00ef" ;		
			lab.setLoginId(UserName);
			lab.setPas("123456a");
			lab.setSourceType("MainSite");
			lac.setData(lab);
			lab.setClientIp(TestDataManager.getRandomIp());
			lac.callService();		
			Logger.verifyEquals(true, lac.getSuccess(), "验证Success");
			Logger.verifyEquals(UserName, lac.getUserData().getLoginId(), "验证UserName");
			HashMap m = new HashMap();
			m.put("Uid", UserId);
			List<Map> list = new LoginHistoryWapper().selectTokenHistoryByUid(m);
			Logger.verifyEquals(true, list.size()>0, "验证Ymt_TokenHistory表记录");
//			Logger.verifyNotNull(AccessToken, "验证AccessToken");
			Logger.verifyEquals(UserId, lac.getUserData().getUserId(), "验证UserId");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	/*****************用于IP区域和设备的认证测试******************/
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_LoginAuth_008(){
		Logger.start(true, "常用设备登陆(即已认证过的设备), 登陆成功");
		try{
			int userId = 913;
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			userWapper.updatePwdByUid(userId);
			
			String deviceId = "normalIOS";
			Map<String, Object> authDevice = authWapper.getDeviceAuthByUserIdAndDeviceId(userId, deviceId).get(0);
			Logger.verifyNotNull(authDevice, "验证设备已认证过");
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp("1.1.7.1");
			lab.setSourceType("app");
			lab.setDeviceId(deviceId);
			lab.setClientId("aaaa");
			lac.setData(lab);
			lac.callService();
			
			Logger.verifyEquals("true", lac.getString("Success"), "验证登陆成功");
			Logger.verifyEquals(userId, lac.getUserData().getUserId(), "验证用户ID");
			Logger.verifyEquals(user.gettPas(), lac.getUserData().getTradingPassword(), "验证交易密码");
			Logger.verifyEquals(user.getlBills().getLoginId(), lac.getUserData().getLoginId(), "验证登陆ID");
			Logger.verifyEquals(user.getlBills().getEmail(), lac.getUserData().getLoginMail(), "验证邮箱");
			Logger.verifyEquals(user.getlBills().getMobile(), lac.getUserData().getLoginMobile(), "验证手机");
			
			Map userToken = userTokenWapper.getUserTokenByUid(userId);
			Logger.verifyEquals(userToken.get("sId"), lac.getUserData().getSign(), "验证Token信息");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_LoginAuth_009(){
		Logger.start(true, "常用IP区域登陆（已认证过的Ip区域）, 登陆成功");
		try{
			String ip = "2.2.1.3";
			int userId = 968;
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			userWapper.updatePwdByUid(userId);
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp(ip);
			lab.setSourceType("mainsite");
			lac.setData(lab);
			lac.callService();
			
			Logger.verifyEquals("true", lac.getString("Success"), "验证登陆成功");
			Logger.verifyEquals(userId, lac.getUserData().getUserId(), "验证用户ID");
			Logger.verifyEquals(user.gettPas(), lac.getUserData().getTradingPassword(), "验证交易密码");
			Logger.verifyEquals(user.getlBills().getLoginId(), lac.getUserData().getLoginId(), "验证登陆ID");
			Logger.verifyEquals(user.getlBills().getEmail(), lac.getUserData().getLoginMail(), "验证邮箱");
			Logger.verifyEquals(user.getlBills().getMobile(), lac.getUserData().getLoginMobile(), "验证手机");
			
			Map userToken = userTokenWapper.getUserTokenByUid(userId);
			Logger.verifyEquals(userToken.get("sId"), lac.getUserData().getSign(), "验证Token信息");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	//修改配置文件limit 不然6次会优先提示limit
	//<add key ="LoginIdCountLimitTimeSpan" value ="00:01:00"/>
    //<add key ="LoginIdLimit" value="6"/>
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_LoginAuth_010(){
		Logger.start(false, "PC端10分钟内登陆密码错误"+LoginSafeConfiguration.PC_LOGINPAS_CHECKSPEC+"次，提示需要身份验证");
		try{
			String ip = "1.9.5.3";
			Map m=UserCallService.registerByMobile();
			String loginid=m.get("username").toString();
			
			Logger.comment("前置条件准备");
			Logger.comment("如果ip（"+ip+"）已进黑名单，则删除，并且删除其近一天的历史登陆记录");
			checkIpLoginHistory(ip, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
			Logger.comment("删除用户的历史登陆记录，以免对场景产生影响");
			checkLoginIDLoginHistory((Integer)m.get("userid"), loginid, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
			
			Logger.comment("使用同一IP同一用户连续进行错误密码"+LoginSafeConfiguration.PC_LOGINPAS_CHECKSPEC+"次登陆");
			for(int i=0; i<LoginSafeConfiguration.PC_LOGINPAS_CHECKSPEC; i++){
				lab = new LoginAuthBean();
				lac = new LoginAuthCall();
				lab.setLoginId(loginid);
				lab.setClientIp(ip);
				lab.setSourceType("mainsite");
				lab.setPas("123");
				lac.setData(lab);
				lac.callService();
				Logger.verifyEquals("false", lac.getString("Success"), "验证登陆失败");
				Logger.verifyEquals("用户名或登录密码错误", lac.getMsg(), "验证登陆信息");
				Logger.verifyEquals("LoingIdOrPasError", new JSONObject(lac.getString("Result")).get("Code"), "验证Code信息");
			}
			
			Logger.comment("开始用正确的密码登陆");
			lab = new LoginAuthBean();
			lac = new LoginAuthCall();
			lab.setLoginId(loginid);
			lab.setClientIp(ip);
			lab.setSourceType("mainsite");
			lab.setPas("123456a");
			lac.setData(lab);
			lac.callService();
			LoginSafeConfiguration.checkLoginStatus(lac);
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	//修改配置  <add key="backlistloginfail" value="10" />
	//<add key ="LoginIdLimit" value="10"/>
	public void Tc_LoginAuth_011(){
		Logger.start(false, "App端10分钟内登陆密码错误6次，提示需要身份验证");
		try{
			Map UserMap = UserCallService.registerByMobile();
			String AccessToken = (String) UserMap.get("accesstoken");
			int UserId = (Integer) UserMap.get("userid");
			String UserName = (String) UserMap.get("phone");
			String deviceId = TestDataManager.getRandomUUID().toString();

			Logger.comment("前置条件准备");
			Logger.comment("如果设备（"+deviceId+"）已进黑名单，则删除");
			checkDeviceLoginHistory(deviceId, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
			Logger.comment("删除用户的历史登陆记录，以免对场景产生影响");
			checkLoginIDLoginHistory(UserId, UserName, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
			
			Logger.comment("使用同一设备同一用户连续进行错误密码"+LoginSafeConfiguration.APP_LOGINPAS_CHECKSPEC+"次登陆");
			for(int i=0; i<LoginSafeConfiguration.APP_LOGINPAS_CHECKSPEC; i++){
					lab = new LoginAuthBean();
					lac = new LoginAuthCall();
					lab.setLoginId(UserName);
					lab.setClientIp("1.2.1.1");
					lab.setSourceType("app");
					lab.setPas("123");
					lab.setDeviceId(deviceId);
					lab.setClientId(deviceId);
					lac.setData(lab);
					lac.callService();
					Logger.verifyEquals("false", lac.getString("Success"), "验证登陆失败");
					Logger.verifyEquals("用户名或登录密码错误", lac.getMsg(), "验证登陆信息");
					Logger.verifyEquals("LoingIdOrPasError", new JSONObject(lac.getString("Result")).get("Code"), "验证Code信息");
			}
			
			Logger.comment("开始用正确的密码登陆");
			lab = new LoginAuthBean();
			lac = new LoginAuthCall();
			lab.setLoginId(UserName);
			lab.setClientIp("1.10.10.1");
			lab.setSourceType("app");
			lab.setPas("123456a");
			lab.setDeviceId(deviceId);
			lab.setClientId(deviceId);
			lac.setData(lab);
			lac.callService();
			LoginSafeConfiguration.checkLoginStatus(lac);
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_LoginAuth_012(){
		Logger.start(false, "某个IP在1分内连续进行"+LoginSafeConfiguration.IP_LOGIN_SUCCESS_LIMIT+"次的登录成功记录，提示需要身份验证");
		try{
			if(LoginSafeConfiguration.IP_LOGIN_SUCCESS_LIMIT>0){
				List<Map<String, Object>> authIPArea = authWapper.getIPAuthData(200, YMTDateUtil.getBeforeOrNextDay(-90),"China","Fujian");
				if(authIPArea==null){
					Assert.fail("没有测试数据");
				}
				String ip = "1.0.3.255";//TestDataManager.getRandomIp();//随机获取Ip(China, Fujian)
				Logger.comment("删除IP黑名单和历史登陆数据(如果存在)");
				checkIpLoginHistory(ip, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
				
				Logger.comment("用同一IP不同的用户进行正确登陆"+LoginSafeConfiguration.IP_LOGIN_SUCCESS_LIMIT+"次");
				for(int j=0; j<LoginSafeConfiguration.IP_LOGIN_SUCCESS_LIMIT; j++){
					ULC201406Bean user = userWapper.getULCInfoByUid((Integer)authIPArea.get(j).get("UserId"));
					userWapper.updatePwdByUid(user.getuId());
					userWapper.unlockUserByUid(user.getuId());
					lab = new LoginAuthBean();
					lac = new LoginAuthCall();
					lab.setLoginId(user.getlBills().getLoginId());
					lab.setClientIp(ip);
					lab.setSourceType("mainsite");
					lab.setPas("123456a");
					lac.setData(lab);
					lac.callService();
					Logger.verifyEquals("true", lac.getString("Success"), "验证登陆成功");
				}
				Thread.sleep(1000);
				Logger.comment("进行第"+(LoginSafeConfiguration.IP_LOGIN_SUCCESS_LIMIT+1)+"次登陆");
				int userId = (Integer)authIPArea.get(2).get("UserId");
				ULC201406Bean user = userWapper.getULCInfoByUid(userId);
				lab = new LoginAuthBean();
				lac = new LoginAuthCall();
				lab.setLoginId(user.getlBills().getLoginId());
				lab.setClientIp(ip);
				lab.setSourceType("mainsite");
				lab.setPas("123456a");
				lac.setData(lab);
				lac.callService();
				LoginSafeConfiguration.checkLoginStatusWithBlackIp(lac, true, ip);
			}else{
				Logger.verifyEquals(0, LoginSafeConfiguration.IP_LOGIN_SUCCESS_LIMIT, "次数为0，此case无需运行");
			}
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_LoginAuth_013(){
		Logger.start(false, "某个设备号在1分内连续进行20次的登录成功记录，提示需要身份验证");
		try{
			String deviceId = "aaaa1";
			List<Map<String, Object>> authDevice = authWapper.getDeviceAuthData(200, YMTDateUtil.getBeforeOrNextDay(-90), deviceId);
			if(authDevice==null){
				Assert.fail("没有测试数据");
			}
			Logger.comment("删除设备黑名单和历史登陆数据(如果存在)");
			checkDeviceLoginHistory(deviceId, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
			
			Logger.comment("用同一设备不同的用户进行正确登陆"+LoginSafeConfiguration.DEVICE_LOGIN_SUCCESS_LIMIT+"次");
			int limit = LoginSafeConfiguration.DEVICE_LOGIN_SUCCESS_LIMIT;
			for(int j=0; j<limit; j++){
				ULC201406Bean user = userWapper.getULCInfoByUid((Integer)authDevice.get(j).get("UserId"));
				if(user!=null){
					lab = new LoginAuthBean();
					lac = new LoginAuthCall();
					lab.setLoginId(user.getlBills().getLoginId());
					lab.setClientIp("1.11.11.1");
					lab.setSourceType("app");
					lab.setPas("123456a");
					lab.setDeviceId(deviceId);
					lab.setClientId("aaaa12");
					lac.setData(lab);
					lac.callService();
					Logger.verifyEquals("true", lac.getString("Success"), "验证登陆成功");
				}else{
					++limit;
				}
			}
			
			Thread.sleep(1000);
			Logger.comment("进行第"+(LoginSafeConfiguration.DEVICE_LOGIN_SUCCESS_LIMIT+1)+"次登陆");
			int userId = (Integer)authDevice.get(7).get("UserId");
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			lab = new LoginAuthBean();
			lac = new LoginAuthCall();
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setClientIp("1.2.1.1");
			lab.setSourceType("app");
			lab.setPas("123456a");
			lab.setDeviceId(deviceId);
			lab.setClientId("aaaa12");
			lac.setData(lab);
			lac.callService();
			LoginSafeConfiguration.checkLoginStatusWithBlackIp(lac, true, deviceId);
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_LoginAuth_014(){
		Logger.start(false, "设备号不存在设备认证库中，提示需要身份验证");
		try{
			Logger.comment("前置条件准备");
			int userId = 438;
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			userWapper.updatePwdByUid(userId);
			String deviceId = TestDataManager.getRandomNum(6);
			Logger.comment("如果设备已认证过，则删除此认证数据");
			authWapper.deleteDeviceData(userId, deviceId);
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp("1.1.9.1");
			lab.setSourceType("app");
			lab.setDeviceId(deviceId);
			lab.setClientId("aaaa");
			lac.setData(lab);
			lac.callService();
			LoginSafeConfiguration.checkLoginStatus(lac);;

			Logger.comment("验证该设备已存入认证库中");
			Thread.sleep(1000);
			Map<String, Object> authDevice = authWapper.getDeviceAuthByUserIdAndDeviceId(user.getuId(), deviceId).get(0);
			Logger.verifyEquals(0, authDevice.get("AuthStatus"), "验证认证状态");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_LoginAuth_015(){
		Logger.start(true, "用户第一次使用IP区域登陆验证，提示登陆成功，该用户Ip区域存入IP认证库");
		try{
			Logger.comment("前置条件准备");
			Map m=UserCallService.registerUser(TestDataManager.getEmail(), null,null);
			Logger.debug(m);
			String ip = "100.100.100.100"; //Shared address,Shared address
			int userId = Integer.valueOf(m.get("userId").toString());
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			userWapper.updatePwdByUid(userId);
			Logger.comment("删除Ip黑名单，删除IP在一天内的历史记录");
			checkIpLoginHistory(ip, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp(ip);
			lab.setSourceType("mainsite");
			lac.setData(lab);
			lac.callService();
			Logger.verifyEquals("true", lac.getString("Success"), "验证登陆成功");
			Thread.sleep(1000);
			Logger.comment("验证该IP区域已存入认证库中");
			Map<String, Object> ipAuth = authWapper.getIPAuthByUserIdAndArea(userId, "Shared address", "Shared address", "*");
			Logger.verifyNotNull(ipAuth, "验证IP认证已存入数据库中");
			Logger.verifyEquals(200, ipAuth.get("AuthStatus"), "验证认证状态为成功");
		}catch (Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P2.class)
	@TestCase
	public void Tc_LoginAuth_016(){
		Logger.start(false, "设备号最后一次token认证时间大于90天");
		try{
			Logger.comment("前置条件准备");
			ULC201406Bean user = userWapper.getULCInfoByUid(1204);
			userWapper.updatePwdByUid(1204);
			String deviceId = "tokenOld";
			String dateTime = YMTDateUtil.getBeforeOrNextDay(-100);
		
			Logger.comment("如果认证数据库中不存在该设备的Token记录，则插入token数据，并将token的最后更新时间更改为90天以前");
			Map<String, Object> deviceAuth = authWapper.getDeviceAuthByUserIdAndDeviceId(user.getuId(), deviceId).get(0);
			if(deviceAuth==null){
				authWapper.insertDeviceTokenAuthHistory(user.getuId(), deviceId, 1, dateTime, dateTime);
				authWapper.insertDataToUserDeviceAuth(user.getuId(), deviceId, 200, dateTime, 
						dateTime, "app", dateTime, 1, "");
			}else{
				authWapper.updateTokenUpdateTime(user.getuId(), deviceId, dateTime);
			}
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp("1.105.1.2");
			lab.setSourceType("app");
			lab.setDeviceId(deviceId);
			lac.setData(lab);
			lac.callService();
			
			LoginSafeConfiguration.checkLoginStatus(lac);
			
		} catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P2.class)
	@TestCase
	public void Tc_LoginAuth_017(){
		Logger.start(false, "IP最后一次token认证时间大于90天，提示需要认证");
		try{
			String ip = "1.1.10.1";//China,Guangdong,*
			int userId = 705;
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			
			Logger.comment("如果认证数据库中不存在该IP的Token记录，则插入token数据，并将token的最后更新时间更改为90天以前");
			Map<String, Object> ipAuth = authWapper.getIPAuthByUserIdAndArea(userId, "China", "Guangdong", "*");
			String dateTime = YMTDateUtil.getBeforeOrNextDay(-100);
			if(ipAuth==null){
				authWapper.insertIPTokenAuthHistory(userId, "China", "Guangdong", "*", dateTime, dateTime);
				authWapper.insertUserIpAuth(userId, "China", "Guangdong", "*", 200, dateTime, dateTime, "mainsite", dateTime, dateTime);
			}else{
				authWapper.updateTokenUpdateTime(userId, "China", "Guangdong", "*", dateTime);
			}
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp(ip);
			lab.setSourceType("www.ymatou.com");
			lac.setData(lab);
			lac.callService();
			
			LoginSafeConfiguration.checkLoginStatus(lac);
			
		} catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_LoginAuth_018(){
		Logger.start(false, "App端，使用上次认证失败过的设备登陆,提示需要认证");
		try{
			ULC201406Bean user = userWapper.getULCInfoByUid(572);
			String deviceId = "Authfailed";
			String dateTime = YMTDateUtil.getBeforeOrNextDay(-1);
			Logger.comment("如果认证数据库中不存在该设备的认证记录，则插入此数据，否则更改此认证状态为失败状态(-200)");
			Map<String, Object> deviceAuth = authWapper.getDeviceAuthByUserIdAndDeviceId(user.getuId(), deviceId).get(0);
			if(deviceAuth==null){
				authWapper.insertDataToUserDeviceAuth(user.getuId(), deviceId, -200, dateTime, 
						dateTime, "app", dateTime, 1, "");
			}else if(deviceAuth.get("AuthStatus").toString()!="200"){
				authWapper.updateAuthStatus(user.getuId(), deviceId, -200);
			}
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp("1.100.1.2");
			lab.setSourceType("app");
			lab.setDeviceId(deviceId);
			lac.setData(lab);
			lac.callService();
			
			LoginSafeConfiguration.checkLoginStatus(lac);
			
		} catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_LoginAuth_019(){
		Logger.start(false, "PC端，使用上次认证失败过的IP登陆");
		try{
			String ip = "1.11.10.1";
			ULC201406Bean user = userWapper.getULCInfoByUid(571);
			
			Logger.comment("如果认证数据库中不存在该Ip的认证记录，则插入此数据，否则更改此认证状态为失败状态(-200)");
			Map<String, Object> ipAuth = authWapper.getIPAuthByUserIdAndArea(user.getuId(), "The Republic of Korea", "The Republic of Korea", "*");
			String dateTime = YMTDateUtil.getBeforeOrNextDay(-10);
			if(ipAuth==null){
				authWapper.insertUserIpAuth(user.getuId(), "The Republic of Korea", "The Republic of Korea", "*", -200, dateTime, dateTime, "mainsite", dateTime, dateTime);
			}else{
				authWapper.updateAuthStatus(user.getuId(), "The Republic of Korea", "The Republic of Korea", "*", -200);
			}
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp(ip);
			lab.setSourceType("mainsite");
			lac.setData(lab);
			lac.callService();
			
			LoginSafeConfiguration.checkLoginStatus(lac);
			
		} catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_LoginAuth_020(){
		Logger.start(false, "通过PC，1分钟内登陆失败20次，ip进入黑名单");
		try{
			if(LoginSafeConfiguration.IP_LOGIN_FAIL_LIMIT>0){
				List<Map<String, Object>> authIPArea = authWapper.getIPAuthData(200, YMTDateUtil.getBeforeOrNextDay(-90),"United States","America");
				if(authIPArea==null){
					Assert.fail("没有测试数据");
				}
				String ip = "11.100.100.100";
				checkIpLoginHistory(ip, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
				
				Logger.comment("用同一IP不同的用户进行错误密码登陆"+LoginSafeConfiguration.IP_LOGIN_FAIL_LIMIT+"次");
				int limit = LoginSafeConfiguration.IP_LOGIN_FAIL_LIMIT;
				for(int j=0; j<limit; j++){
					ULC201406Bean user = userWapper.getULCInfoByUid((Integer)authIPArea.get(j).get("UserId"));
					if(user!=null){
						lab = new LoginAuthBean();
						lac = new LoginAuthCall();
						lab.setLoginId(user.getlBills().getLoginId());
						lab.setClientIp(ip);
						lab.setSourceType("www.ymatou.com");
						lab.setPas("456789");
						lac.setData(lab);
						lac.callService();
						Logger.verifyEquals("false", lac.getString("Success"), "验证登陆失败");
						Logger.verifyEquals("用户名或登录密码错误", lac.getMsg(), "验证登陆信息");
					}else{
						++limit;
					}
				}
				
				Logger.comment("进行第"+(LoginSafeConfiguration.IP_LOGIN_FAIL_LIMIT+1)+"次登陆");
				int userId = (Integer)authIPArea.get(10).get("UserId");
				ULC201406Bean user = userWapper.getULCInfoByUid(userId);
				userWapper.updatePwdByUid(userId);
				lab = new LoginAuthBean();
				lac = new LoginAuthCall();
				lab.setLoginId(user.getlBills().getLoginId());
				lab.setClientIp(ip);
				lab.setSourceType("www.ymatou.com");
				lab.setPas("123456a");
				lac.setData(lab);
				lac.callService();
				LoginSafeConfiguration.checkLoginStatusWithBlackIp(lac, true, ip);
			}else{
				Logger.verifyEquals(0, LoginSafeConfiguration.IP_LOGIN_FAIL_LIMIT, "次数为0，无需运行此case");
			}
		} catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_LoginAuth_021(){
		Logger.start(false, "某个设备号在1分内连续进行20次的登录失败记录，提示需要身份验证");
		try{
			List<Map<String, Object>> authDevice = authWapper.getDeviceAuthData(200, YMTDateUtil.getBeforeOrNextDay(-90), "BlackDevice");
			if(authDevice==null){
				Assert.fail("没有测试数据");
			}
			String deviceId = "BlackDevice";
			checkDeviceLoginHistory(deviceId, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
			
			Logger.comment("用同一设备不同的用户进行错误密码登陆"+LoginSafeConfiguration.DEVICE_LOGIN_FAIL_LIMIT+"次");
			for(int j=0; j<LoginSafeConfiguration.DEVICE_LOGIN_FAIL_LIMIT; j++){
				ULC201406Bean user = userWapper.getULCInfoByUid((Integer)authDevice.get(j).get("UserId"));
				if(user!=null){
					lab = new LoginAuthBean();
					lac = new LoginAuthCall();
					lab.setLoginId(user.getlBills().getLoginId());
					lab.setClientIp("1.115.1.1");
					lab.setSourceType("app");
					lab.setPas("123789");
					lab.setDeviceId(deviceId);
					lab.setClientId(deviceId);
					lac.setData(lab);
					lac.callService();
					Logger.verifyEquals("false", lac.getString("Success"), "验证登陆失败");
					Logger.verifyEquals("用户名或登录密码错误", lac.getMsg(), "验证登陆信息");
				}
			}
			
			Thread.sleep(1000);
			Logger.comment("进行第"+(LoginSafeConfiguration.DEVICE_LOGIN_FAIL_LIMIT+1)+"次登陆");
			int userId = (Integer)authDevice.get(4).get("UserId");
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			lab = new LoginAuthBean();
			lac = new LoginAuthCall();
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setClientIp("1.115.1.1");
			lab.setSourceType("app");
			lab.setPas("123456a");
			lab.setDeviceId(deviceId);
			lab.setClientId(deviceId);
			lac.setData(lab);
			lac.callService();
			LoginSafeConfiguration.checkLoginStatusWithBlackIp(lac, true, deviceId);
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_LoginAuth_022(){
		Logger.start(true, "Pc端，使用IP区域库中不存在的IP进行登陆，登陆成功");
		try{
			Map<String, Object> authIPArea = authWapper.getIPAuth(200, YMTDateUtil.getBeforeOrNextDay(-90),"China","Fujian");
			if(authIPArea==null){
				Assert.fail("没有测试数据");
			}
			String ip = "266.1.3.1";
			int userId = (Integer)authIPArea.get("UserId");
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			userWapper.updatePwdByUid(userId);
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp(ip);
			lab.setSourceType("app");
			lac.setData(lab);
			lac.callService();
			
			Logger.verifyEquals("true", lac.getString("Success"), "验证登陆成功");
			Logger.verifyEquals(userId, lac.getUserData().getUserId(), "验证用户ID");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_LoginAuth_023(){
		Logger.start(true, "未输入设备号，clientID不存在设备认证库中，登陆成功");
		try{
			int userId = 6073;
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			userWapper.updatePwdByUid(userId);
			String clientId = "NotExistInDB";
			authWapper.deleteDeviceData(userId, clientId);
			
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp("1.1.9.1");
			lab.setSourceType("app");
			lab.setClientId(clientId);
			lac.setData(lab);
			lac.callService();
			
			Logger.verifyEquals("true", lac.getString("Success"), "验证登陆成功");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P2.class)
	@TestCase
	public void Tc_LoginAuth_024(){
		Logger.start(false, "用户在其他IP区域认证过，再次使用未认证过的Ip区域登陆，即该Ip区域不存入IP认证库，提示需要认证");
		try{
			Map m=UserCallService.registerByMobile();
			Logger.debug(m);
			String ip = "100.100.100.100"; //Shared address,Shared address
			int userId = Integer.valueOf(m.get("userid").toString());
			ULC201406Bean user = userWapper.getULCInfoByUid(userId);
			userWapper.updatePwdByUid(userId);
			checkIpLoginHistory(ip, YMTDateUtil.getDateForMongoFormat(-1, 0, 0));
			Logger.comment("登陆此用户");
			lab.setLoginId(user.getlBills().getLoginId());
			lab.setPas("123456a");
			lab.setClientIp(ip);
			lab.setSourceType("mainsite");
			lac.setData(lab);
			lac.callService();
			Logger.verifyEquals("true", lac.getString("Success"), "验证登陆成功");
			Thread.sleep(1000);
			Map<String, Object> ipAuth = authWapper.getIPAuthByUserIdAndArea(userId, "Shared address", "Shared address", "*");
			Logger.verifyNotNull(ipAuth, "验证IP认证已存入数据库中");
			Logger.verifyEquals(200, ipAuth.get("AuthStatus"), "验证认证状态为成功");
			Thread.sleep(2000);
			String newIp = "10.100.100.100";//LAN, LAN
			lab.setClientIp(newIp);
			lac = new LoginAuthCall();
			lac.setData(lab);
			lac.callService();
			LoginSafeConfiguration.checkLoginStatus(lac);
			Thread.sleep(1000);
			Map<String, Object> ipAuth1 = authWapper.getIPAuthByUserIdAndArea(userId, "LAN", "LAN", "*");
			Logger.verifyNotNull(ipAuth1, "验证IP认证已存入数据库中");
			Logger.verifyEquals(0, ipAuth1.get("AuthStatus"), "验证认证状态为成功");
		}catch (Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_LoginAuth_025(){
		Logger.start(true,"注册用户第一次在app上登陆，登入认证成功");
		try {
			Logger.comment("前置条件准备");
			String phone = TestDataManager.getPhoneNum();
			String email = TestDataManager.getEmail();
			Map UserMap = UserCallService.registerUser(email, phone,null);
			String AccessToken = (String) UserMap.get("token");
			int UserId = (Integer) UserMap.get("userId");
			String UserName = (String) UserMap.get("loginId");
			Thread.sleep(5000);
			HashMap m = new HashMap();
			m.put("Uid", UserId);
			List<Map> list = new LoginHistoryWapper().selectUserRegHistoryByUid(m);
			Logger.verifyEquals(1, list.size(), "验证UserRegHistory表记录");
			
			Logger.comment("开始登陆认证");
			lab.setLoginId(UserName);
			lab.setClientId("test_"+TestDataManager.getRandomNum(10));
			lab.setClientIp(TestDataManager.getRandomIp());
			lab.setPas("123456a");
			lab.setSourceType("app");
			lac.setData(lab);
			lab.setClientIp(TestDataManager.getRandomIp());
			lac.callService();
			Logger.verifyEquals(true, lac.getSuccess(), "验证Success");
			Logger.verifyEquals(phone, lac.getUserData().getLoginMobile(), "验证UserName");
			Logger.verifyEquals(UserId, lac.getUserData().getUserId(), "验证UserId");
			Logger.verifyEquals(UserName.toLowerCase(), lac.getUserData().getLoginId(), "验证登陆ID");
			Logger.verifyEquals(email.toLowerCase(), lac.getUserData().getLoginMail(), "验证登录邮箱");
			Logger.verifyEquals(AccessToken, lac.getUserData().getSign(), "验证Token信息");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	/**
	 * 删除Ip黑名单，删除IP在一段时间内的历史记录
	 * @param ip IP
	 * @param dateTime 删除此时间之后的历史记录（从现在到dateTime为止的历史记录）
	 * @throws Exception
	 */
	public void checkIpLoginHistory(String ip, String dateTime) throws Exception{
		if(DELETELOGINHISTORY){
			ymtblacklistuserWapper.deleteData(ip);
			mloginHistoryWapper.deleteByIp(ip, dateTime);
		}
	}
	
	/**
	 * 删除设备黑名单，删除设备在一段时间内的历史记录
	 * @param deviceId 设备Id
	 * @param dateTime 删除此时间之后的历史记录（从现在到dateTime为止的历史记录）
	 * @throws Exception
	 */
	public void checkDeviceLoginHistory(String deviceId, String dateTime) throws Exception{
		if(DELETELOGINHISTORY){
			ymtblacklistuserWapper.deleteData(deviceId);
			mloginHistoryWapper.deleteByDeviceId(deviceId, dateTime);
		}
	}
	
	/**
	 * 删除用户黑名单，删除用户在一段时间内的登陆记录
	 * @param uId 用户Id
	 * @param loginId 登陆Id
	 * @param dateTime 删除此时间之后的历史记录（从现在到dateTime为止的历史记录）
	 * @throws Exception
	 */
	public void checkLoginIDLoginHistory(int uId, String loginId, String dateTime) throws Exception{
		if(DELETELOGINHISTORY){
			ymtblacklistuserWapper.deleteData(uId);
			mloginHistoryWapper.deleteByLoginId(loginId, dateTime);
		}
	}
}